//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/practice/ct_enum.dart';
import 'package:hktk_app/ienum/question/answer_type_enum.dart';
import 'package:hktk_app/ienum/question/collect_type_enum.dart';
import 'package:hktk_app/ienum/question/question_type_enum.dart';
import 'package:hktk_app/model/data_model.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/question/paper_data_model.dart';
import 'package:hktk_app/model/subject/upload_answer_model.dart';
import 'package:hktk_app/model/subject/upload_collection_model.dart';
import 'package:hktk_app/model/subject/upload_save_model.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/my_util.dart';


/// 试题相关工具类

/// 试题页面退出方法
void questionBackFun({
  required BuildContext context,
  required DataModel dataModel,
  required PaperDataModel paperDataModel,
}) {


  CtEnum rType = paperDataModel.rType;
  if (rType == CtEnum.everyday ||
      rType == CtEnum.chapter ||
      rType == CtEnum.paperRecordChapterPractice) {
    if (paperDataModel.dc != 0 || paperDataModel.cc != 0) {
      _uploadRe(dataModel, paperDataModel);
      if (paperDataModel.cc != 0) {
        _uploadSc(dataModel, paperDataModel);
      }
      if (paperDataModel.dc != 0) {
        _uploadDa(dataModel, paperDataModel);
      }
    }
    if (rType == CtEnum.chapter) {
      // 章节练习，发送刷新做题数据方法，延时800毫秒
      // 为了更快，推荐部分更新

      // Future.delayed(const Duration(milliseconds: 800)).then((value) {
      //   eventBus.fire(EventChapterBack(
      //     chapterId: paperDataModel.id
      //   ));
      // });
      eventBus.fire(EventChapterBack(
          chapterId: paperDataModel.id
      ));
    }
  }
  // 退出页面
  Navigator.pop(context);
}

/// 发送集合统计数据
void _uploadRe(DataModel dataModel, PaperDataModel paperData) {
  UploadSaveModel saveModel = UploadSaveModel(
    dc: paperData.dc,
    ec: paperData.ec,
    cc: paperData.cc,
  );
  try {
    SubjectDao.saveChapterRecords(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      collectId: paperData.collectId,
      recordsType: paperData.rType,
      data: saveModel,
    );
  } catch (e) {
    debugPrint("保存章节集合统计数据 发生异常 ===> $e");
    if (e is DaoException) {
      debugPrint(e.msg);
    }
  }
}

/// 发送收藏请求
_uploadSc(DataModel dataModel, PaperDataModel paperData) {
  // 发送收藏所需数据
  List<String> scRemIds = [];
  Map<String, UploadCollectionModel> scData = {};
  Map<String, int> scCdata = {};
  for (DtkInfoModel dtk in paperData.dtkList) {
    if (dtk.collType == CollectTypeEnum.cancel) {
      scRemIds.add(dtk.id);
    } else if (dtk.collType == CollectTypeEnum.suc) {
      scCdata[dtk.id] = dtk.collData ?? 0;
      if (dtk.collData != null) {
        scData[dtk.id] = _getQUpload(dtk, paperData);
      }
    }
  }

  try {
    // 发送收藏请求
    SubjectDao.pushNewCollect(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      collectId: paperData.collectId,
      collectName: paperData.name,
      recordsType: paperData.rType,
      removeIds: scRemIds,
      data: scData,
      cdata: scCdata,
    );
  } catch (e) {
    debugPrint("集合做题退出时保存试题收藏数据 发生异常 ===> $e");
    if (e is DaoException) {
      debugPrint(e.msg);
    }
  }
}

/// 获取上传相关信息
UploadCollectionModel _getQUpload(
    DtkInfoModel dtk,
    PaperDataModel paperData,
    ) {
  return UploadCollectionModel(
    qid: dtk.id,
    qt: dtk.type.code,
    sn: dtk.sign,
    t: dtk.collData ?? 0,
    tr: dtk.type.desc,
    st: dtk.st,
    as: dtk.getUserAnsStr(),
    cid: paperData.collectId,
    cn: paperData.name,
    ct: paperData.rType,
  );
}

/// 发送答案请求
_uploadDa(DataModel dataModel, PaperDataModel paperData) {
  // 发送答案所需数据
  Map<String, UploadAnswerModel> daData = {};
  String lastId = paperData.dtkList[0].id;
  // 统计错题记录
  Map<String, UploadCollectionModel> ctData = {};
  for (DtkInfoModel dtk in paperData.dtkList) {
    if (dtk.ansType != AnswerTypeEnum.notDone) {
      lastId = dtk.id;
      daData[dtk.id] = _getDaUpload(dtk);
      if (dtk.ansType == AnswerTypeEnum.error) {
        ctData[dtk.id] = _getQUpload(dtk, paperData);
      }
    }
  }

  try {
    // 发送答案请求
    SubjectDao.pushChapterAnswer(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      collectId: paperData.collectId,
      recordsType: paperData.rType,
      collectName: paperData.name,
      lastId: lastId,
      totalCount: paperData.dtkList.length,
      data: daData,
    );
  } catch (e) {
    debugPrint("练习模式退出时提交答案 发生异常 ===> $e");
    if (e is DaoException) {
      debugPrint(e.msg);
    }
  }

  // 判断是否有错题记录，有就发送
  if (ctData.isNotEmpty) {
    try {
      // 发送错题记录请求
      SubjectDao.pushCollectErrorAnswer(
        industryCode: dataModel.industryId,
        examId: dataModel.examId,
        categoryId: dataModel.categoryId,
        collectId: paperData.collectId,
        collectName: paperData.name,
        recordsType: paperData.rType,
        data: ctData,
      );
    } catch (e) {
      debugPrint("集合做题退出是保存错题数据 发生异常 ===> $e");
      if (e is DaoException) {
        debugPrint(e.msg);
      }
    }
  }
}

/// 获取答案上传相关信息
UploadAnswerModel _getDaUpload(DtkInfoModel dtk) {
  return UploadAnswerModel(
    as: dtk.getUserAnsStr(),
    t: dtk.ansDate ?? 0,
    rt: dtk.ansType == AnswerTypeEnum.success,
    newDo: dtk.ansDate != null,
    st: dtk.st,
    tr: dtk.type.name,
    sn: dtk.sign,
  );
}

// <================================== 分割线 ==================================>

/// 试题考试页面退出方法
void questionExamBackFun({
  required BuildContext context,
  required QuestionTypeEnum questionType,
  required int questionIndex,
  required DataModel dataModel,
  required PaperDataModel paperDataModel,
}) {
  debugPrint("questionUtil 工具 -> 考试试题退出保存相关数据方法执行 ===> ");
  if (questionType == QuestionTypeEnum.exam) {
    if(paperDataModel.rType == CtEnum.paperRecordPaperLibrary) {
      // 开启加载框，发送信息获取当前页面的答案
      DtkInfoModel dtk = paperDataModel.dtkList[questionIndex];
      if (MyUtil.getDXT(dtk.type) || MyUtil.getPDT(dtk.type)) {
        questionExamBackSaveFun(
          context: context,
          questionType: questionType,
          dataModel: dataModel,
          paperDataModel: paperDataModel,
        );
      } else {
        eventBus.fire(EventQuestionExamJj(id: dtk.id, exam: 1));
      }
    } else {
      Navigator.pop(context);
    }
  } else {
    // 退出答案
    Navigator.pop(context);
  }
}

/// 试题考试退出开始保存相关数据方法
void questionExamBackSaveFun({
  required BuildContext context,
  required QuestionTypeEnum questionType,
  required DataModel dataModel,
  required PaperDataModel paperDataModel,
}) {
  // 所需数据
  debugPrint("考试模式退出 ===> ");
  if (questionType == QuestionTypeEnum.exam) {
    _uploadPaperAnswer(
      dataModel: dataModel,
      paperDataModel: paperDataModel,
    );
  }
  // 退出页面
  Navigator.pop(context);
}

/// 发送试卷集合做题答案
void _uploadPaperAnswer({
  required DataModel dataModel,
  required PaperDataModel paperDataModel,
}) {
  if (paperDataModel.dc > 0) {
    int end = DateTime.now().millisecondsSinceEpoch;
    Map<String, RecordModel> data = {};
    String lastId = "";
    for (var dtk in paperDataModel.dtkList) {
      if (dtk.ansType != AnswerTypeEnum.notDone) {
        data[dtk.id] = RecordModel(
          as: dtk.getUserAnsStr(),
          rt: false,
          t: dtk.ansDate,
        );
        lastId = dtk.id;
      }
    }
    // 发送请求
    SubjectDao.savePaperAnswer(
      industryCode: dataModel.industryId,
      examId: dataModel.examId,
      categoryId: dataModel.categoryId,
      recordsId: paperDataModel.id,
      lastId: lastId,
      seconds: end - paperDataModel.startDate,
      cn: paperDataModel.name,
      totalCount: paperDataModel.dtkList.length,
      recordsType: paperDataModel.rType,
      data: data,
    );
  }
}
